<template>
  <div class="student-list-container">
    <el-card>
      <template #header>
        <div class="search-header">
          <el-input
            v-model="searchQuery"
            placeholder="请输入搜索内容"
            clearable
            class="search-input"
            size="default"
          >
            <template #prefix>
              <el-icon class="el-input__icon"><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" size="default" @click="handleSearch"
            >搜索</el-button
          >
          <el-button size="default" @click="handleReset">重置</el-button>
          <el-button type="success" size="default" @click="openAddStudentDialog"
            >添加学生</el-button
          >
          <el-button
            type="danger"
            size="default"
            @click="deleteSelectedStudents"
            :disabled="!selectedStudents.length"
            >批量删除</el-button
          >
          <el-button
            type="info"
            size="default"
            @click="handleExport"
            >导出CSV</el-button>
        </div>
      </template>
      <el-table
        :data="filteredStudents"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        ref="studentTable"
      >
        <el-table-column type="selection" min-width="30" />
        <el-table-column
          type="index"
          align="center"
          label="序号"
          min-width="60"
        >
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          align="center"
          label="姓名"
          min-width="80"
        />
        <el-table-column
          prop="gender"
          align="center"
          label="性别"
          min-width="60"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.gender == 1" type="success">男</el-tag>
            <el-tag v-else type="danger">女</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="age"
          align="center"
          label="年龄"
          min-width="60"
        />
        <el-table-column
          prop="email"
          align="center"
          label="邮箱"
          min-width="180"
        />
        <el-table-column
          prop="phone"
          align="center"
          label="手机号"
          min-width="120"
        />
        <el-table-column
          prop="className"
          align="center"
          label="班级"
          min-width="120"
        />
        <el-table-column label="操作" align="center" min-width="200">
          <template #default="scope">
            <el-button
              text
              type="primary"
              size="default"
              @click="openEditStudentDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              text
              type="danger"
              size="default"
              @click="delStudent(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :pager-count="9"
          layout="prev, pager, next"
          :total="total"
          prev-text="上一页"
          next-text="下一页"
        />
      </div>
    </el-card>

    <!-- 添加/编辑学生弹框 -->
    <el-dialog
      :title="dialogTitle"
      align-center
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        :model="currentStudent"
        :rules="rules"
        ref="studentForm"
        label-width="80px"
        class="dialog-form"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="currentStudent.name"
            placeholder="请输入姓名"
            class="dialog-input"
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="currentStudent.gender" placeholder="请选择性别">
            <el-option
              v-for="item in genderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input
            v-model="currentStudent.age"
            placeholder="请输入年龄"
            class="dialog-input"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="currentStudent.email"
            placeholder="请输入邮箱"
            class="dialog-input"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="currentStudent.phone"
            placeholder="请输入手机号"
            class="dialog-input"
          />
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="currentStudent.classId" placeholder="请选择班级">
            <el-option
              v-for="item in classes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveStudent">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import {
  getStudentList,
  addStudent,
  updateStudent,
  deleteStudent,
  deleteStudents,
  getAllClass,
} from "@/request/request";

const searchQuery = ref("");
const students = ref([]);
const classes = ref([]);

const selectedStudents = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref("添加学生");
const currentStudent = ref({
  name: "",
  gender: null,
  age: null,
  email: "",
  phone: "",
  classId: "",
});

const genderOptions = [
  { label: "男", value: 1 },
  { label: "女", value: 0 },
];

const rules = {
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  classId: [{ required: true, message: "请选择班级", trigger: "blur" }],
  email: [
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "请输入正确的邮箱",
      trigger: "blur",
    },
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
};

// 添加分页相关的响应式数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

onMounted(() => {
  getStudents();
  getClasses();
});

// 获取班级列表
const getClasses = async () => {
  const res = await getAllClass();
  classes.value = res.data;
};

// 获取学生列表
const getStudents = async () => {
  try {
    const res = await getStudentList(currentPage.value, pageSize.value);
    console.log(res);
    students.value = res.data.records;
    total.value = res.data.total; // 设置总数据量
  } catch (error) {
    console.error("获取学生列表失败", error);
  }
};

const handleSearch = () => {
  // 搜索逻辑
};

const filteredStudents = computed(() => {
  if (!searchQuery.value) {
    return students.value; // 当搜索框为空时，直接返回原始数据
  }
  return students.value.filter((student) => {
    return (
      (student.name &&
        student.name.toLowerCase().includes(searchQuery.value.toLowerCase())) ||
      (student.phone && student.phone.includes(searchQuery.value)) ||
      (student.email &&
        student.email.toLowerCase().includes(searchQuery.value.toLowerCase()))
    );
  });
});

const handleReset = () => {
  searchQuery.value = "";
};

const openAddStudentDialog = () => {
  dialogTitle.value = "添加学生";
  currentStudent.value = {
    name: "",
    gender: null,
    age: null,
    email: "",
    phone: "",
    classId: "",
  };
  dialogVisible.value = true;
  // 重置表单校验
  if (studentForm.value) {
    studentForm.value.resetFields();
  }
};

const openEditStudentDialog = (student) => {
  dialogTitle.value = "编辑学生";
  currentStudent.value = { ...student };
  dialogVisible.value = true;
  // 重置表单校验
  if (studentForm.value) {
    studentForm.value.resetFields();
  }
};

const studentForm = ref(null);
const handleSaveStudent = () => {
  studentForm.value.validate(async (valid) => {
    if (valid) {
      if (dialogTitle.value == "添加学生") {
        appendStudent();
      } else {
        editStudent();
      }
    }
  });
};

const appendStudent = async () => {
  // 添加学生逻辑
  const res = await addStudent(currentStudent.value);
  if (res.code == 200) {
    ElMessage.success(res.msg);
    dialogVisible.value = false;
    getStudents();
  } else {
    ElMessage.error(res.msg);
  }
};

const editStudent = async () => {
  // 编辑学生逻辑
  const res = await updateStudent(
    currentStudent.value.id,
    currentStudent.value
  );
  if (res.code == 200) {
    ElMessage.success(res.msg);
    dialogVisible.value = false;
    getStudents();
  } else {
    ElMessage.error(res.msg);
  }
};

const delStudent = async (student) => {
  // 删除学生逻辑
  ElMessageBox.confirm("确定要删除该学生吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteStudent(student.id);
      if (res.code == 200) {
        ElMessage.success(res.msg);
        getStudents();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const deleteSelectedStudents = async () => {
  // 批量删除学生逻辑
  const ids = selectedStudents.value.map((student) => student.id);
  console.log(ids);
  ElMessageBox.confirm("确定要删除这些学生吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteStudents(ids);
      if (res.code == 200) {
        ElMessage.success(res.msg);
        getStudents();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleSelectionChange = (val) => {
  selectedStudents.value = val;
};

// 分页事件
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getStudents();
};

// 导出功能
const handleExport = () => {
  exportToCSV();
};

const exportToCSV = () => {
  const array = [
    ["序号", "姓名", "性别", "年龄", "邮箱", "手机号", "班级"],
    ...students.value.map((student, index) => [
      index + 1,
      student.name,
      student.gender === 1 ? "男" : "女",
      student.age,
      student.email,
      student.phone,
      student.className,
    ]),
  ];

  const csvContent = array.map((row) => row.join(",")).join("\n");
  const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.setAttribute("href", url);
  link.setAttribute("download", "students.csv");
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>

<style scoped>
.search-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.dialog-form {
  text-align: center;
}

.dialog-input {
  width: 100%;
  margin: 0 auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.yellow-button {
  background-color: #e6a23c; /* 黄色背景 */
  border-color: #e6a23c; /* 黄色边框 */
  color: white; /* 白色文字 */
}

.yellow-button:hover {
  background-color: #d8842d; /* 鼠标悬停时的黄色背景 */
  border-color: #d8842d; /* 鼠标悬停时的黄色边框 */
}

.el-button--warning {
  background-color: #e6a23c; /* 黄色背景 */
  border-color: #e6a23c; /* 黄色边框 */
  color: white; /* 白色文字 */
}

.el-button--warning:hover {
  background-color: #d8842d; /* 鼠标悬停时的黄色背景 */
  border-color: #d8842d; /* 鼠标悬停时的黄色边框 */
}
</style>
